package com.homedo.async.mysql.support.mapper.insert;

import com.homedo.async.mysql.support.dataobject.Example;
import com.homedo.async.mysql.support.dml.DMLEnum;
import com.homedo.async.mysql.support.mapper.util.CreateMono4AffectedNumberUtil;
import com.homedo.async.mysql.support.meta.EntityMetaData;
import com.homedo.async.mysql.support.prepare.PrepareObject2Sql;
import com.homedo.async.mysql.support.prepare.PrepareObjectType;
import com.homedo.plainly.logger.Logger;
import com.homedo.plainly.logger.LoggerFactory;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.SqlConnection;
import org.springframework.util.Assert;
import reactor.core.publisher.Mono;

/**
 * @author jgshun
 * @date 2020/3/17 10:41 AM
 */
public class SaveMapperExampleImpl<T, ID> implements SaveMapperExampleI<T, ID> {
    private static final Logger _LOGGER = LoggerFactory.getLogger(SaveMapperExampleImpl.class);

    private Pool pool;

    private EntityMetaData<T> entityMetaData;

    public SaveMapperExampleImpl(Pool pool, EntityMetaData<T> entityMetaData) {
        this.pool = pool;
        this.entityMetaData = entityMetaData;
    }


    @Override
    public Mono<Long> save(Example example) {
        return this.save(example, null);
    }

    @Override
    public Mono<Long> save(Example example, SqlConnection connection) {
        Assert.notNull(example, "The given example must not be null!");

        Object[] prepareSqlArgs = new PrepareObject2Sql(example, entityMetaData, DMLEnum.INSERT, PrepareObjectType.ENTITY_EXAMPLE, false).prepare();

        return this.createSaveMono(prepareSqlArgs, connection);
    }

    private Mono<Long> createSaveMono(Object[] prepareSqlArgs, SqlConnection connection) {
        return CreateMono4AffectedNumberUtil.create(prepareSqlArgs, this.pool, connection);
    }
}
